package com.yxt.function_sdk_share.util;

import android.app.Activity;
import android.app.Application;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.md.livingwidget.toast.PHToast;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.yxt.function_sdk_share.R;
import com.yxt.function_sdk_share.SharePopupWindow;
import com.yxt.function_sdk_share.callback.LoginCallBack;
import com.yxt.function_sdk_share.callback.ShareCallBack;
import com.yxt.function_sdk_share.constants.SHARE_TYPE;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 项目名称：com.yxt.function_sdk_share.util
 * 类名称：ShareUtil
 * 类描述：分享Util类
 * 创建人：wuht
 * 创建时间：2019-12-03 19:09
 */
public class ShareUtil {
    /**
     * 初始化友盟sdk 和  平台设置
     *
     * @param application
     */
    public static void initShare(Application application) {
        UMShareAPI.get(application);
    }


    /**
     * 设置微信秘钥
     *
     * @param id
     * @param secret
     */
    public static void setWeixin(String id, String secret) {
        PlatformConfig.setWeixin(id, secret);
    }

    /**
     * 设置新浪秘钥
     *
     * @param key
     * @param secret
     * @param redirectUrl
     */
    public static void setSinaWeibo(String key, String secret, String redirectUrl) {
//        PlatformConfig.setSinaWeibo(key, secret);
        PlatformConfig.setSinaWeibo(key, secret, redirectUrl);
    }

    /***
     * 设置钉钉秘钥
     * @param key
     */
    public static void setDing(String key) {
        PlatformConfig.setDing(key);
    }

    /***
     * 设置QQ空间秘钥
     * @param id
     * @param key
     */
    public static void setQQZone(String id, String key) {
        PlatformConfig.setQQZone(id, key);
    }

    /***
     * 分享登录
     * @param activity
     * @param share_type
     * @param loginCallBack
     */
    public static void login(final Activity activity, SHARE_TYPE share_type, final LoginCallBack loginCallBack) {

        if (share_type == SHARE_TYPE.QQ || share_type == SHARE_TYPE.WECHAT_FRIENDS) {
            SHARE_MEDIA share_media = getShareMedia(share_type);
            UMShareAPI mShareAPI = UMShareAPI.get(activity);
            mShareAPI.doOauthVerify(activity, share_media, new UMAuthListener() {
                @Override
                public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
                    if (loginCallBack != null) {
                        loginCallBack.onSuccess(getShareType(platform), action, data);
                    }
                }

                @Override
                public void onError(SHARE_MEDIA platform, int action, Throwable t) {
                    if (loginCallBack != null) {
                        loginCallBack.onError(getShareType(platform), action, t);
                    }
                }

                @Override
                public void onCancel(SHARE_MEDIA platform, int action) {
                    if (loginCallBack != null) {
                        loginCallBack.onCancel(getShareType(platform), action);
                    }
                }

                @Override
                public void onStart(SHARE_MEDIA share_media) {
                }
            });
        }
    }

    /**
     * 分享统一 方法, 判断分享内容类型的逻辑不够严密,
     *
     * @param activity
     * @param share_type      --- 分享平台
     * @param imgUrl          --- 图片 url
     * @param title           --- 标题
     * @param text            --- 内容
     * @param shareCallBack-- 回调
     * @param targetUrl       --Web的url
     */
    public static void share(Activity activity, SHARE_TYPE share_type, String imgUrl,
                             String title, String text, String targetUrl, ShareCallBack shareCallBack) {
        if (share_type == SHARE_TYPE.QQ || share_type == SHARE_TYPE.WECHAT_FRIENDS || share_type == SHARE_TYPE.WECHAT_MOMENTS) {
            SHARE_MEDIA share_media = getShareMedia(share_type);
            ShareAction shareAction = new ShareAction(activity);
            shareAction.setPlatform(share_media).setCallback(new ShareListener(activity, shareCallBack));
            if (!TextUtils.isEmpty(targetUrl) && targetUrl.contains("http")) {
                /***
                 *  支持本地图片分享
                 */
                if (!TextUtils.isEmpty(imgUrl)) {
                    if (imgUrl.startsWith("http")) {
                        UMWeb web = new UMWeb(targetUrl);
                        shareAction.withMedia(web);
                        if (!TextUtils.isEmpty(title)) {
                            //标题
                            web.setTitle(title);
                        }
                        if (!TextUtils.isEmpty(text)) {
                            //描述
                            web.setDescription(text);
                        }
                        UMImage image = new UMImage(activity, imgUrl);
                        //                        image.setThumb(new UMImage(activity, imgUrl));
                        image.setThumb(new UMImage(activity, getAppIcon(activity)));
                        web.setThumb(image); //缩略图
                    } else if (imgUrl.startsWith("/")) {
                        File file = new File(imgUrl);
                        if (file.exists()) {
                            UMImage image = new UMImage(activity, file);
                            image.compressStyle = UMImage.CompressStyle.SCALE;
                            Bitmap bitmap = BitmapUtil.File2BitmapUpload(imgUrl);
                            if (bitmap != null) {
                                image.setThumb(new UMImage(activity, bitmap));
                            }
                            if (!TextUtils.isEmpty(title)) {
                                //标题
                                image.setTitle(title);
                            }
                            if (!TextUtils.isEmpty(text)) {
                                //描述
                                image.setDescription(text);
                            }
                            shareAction.withMedia(image);
                        }
                    }
                } else {
                    UMWeb web = new UMWeb(targetUrl);
                    shareAction.withMedia(web);
                    if (!TextUtils.isEmpty(title)) {
                        web.setTitle(title);//标题;
                    }
                    if (!TextUtils.isEmpty(text)) {
                        web.setDescription(text);//描述
                    }
                    UMImage image = new UMImage(activity, getAppIcon(activity));
                    image.setThumb(new UMImage(activity, getAppIcon(activity)));
                    web.setThumb(image); //缩略图
                }
            } else {
                if (!TextUtils.isEmpty(title)) {
                    shareAction.withSubject(title + "");
                }
                if (!TextUtils.isEmpty(text)) {
                    shareAction.withText(text + "");
                }
                if (!TextUtils.isEmpty(imgUrl) && imgUrl.contains("http")) {
                    UMImage image = new UMImage(activity, imgUrl);
                    image.setThumb(new UMImage(activity, getAppIcon(activity)));
                    shareAction.withMedia(image);
                } else {
                    /***
                     *  支持本地图片分享
                     */
                    if (imgUrl.startsWith("/")) {
                        File file = new File(imgUrl);
                        if (file.exists()) {
                            UMImage image = new UMImage(activity, file);
                            Bitmap bitmap = BitmapUtil.File2BitmapUpload(imgUrl);
                            image.compressStyle = UMImage.CompressStyle.SCALE;
                            if (bitmap != null) {
                                image.setThumb(new UMImage(activity, bitmap));
                            }

                            shareAction.withMedia(image); //缩略图
                        }
                    } else {
                        //                        UMImage image = new UMImage(activity, getAppIcon(activity));
                        //                        image.setThumb(new UMImage(activity, getAppIcon(activity)));
                        //                        shareAction.withMedia(image);
                        if (!TextUtils.isEmpty(text)) {
                            shareAction.withText(text);
                        } else {
                            UMImage image = new UMImage(activity, getAppIcon(activity));
                            image.setThumb(new UMImage(activity, getAppIcon(activity)));
                            shareAction.withMedia(image);
                        }

                    }
                }
            }
            shareAction.share();
        }
    }


    /***
     * 获取程序 图标
     */
    public static int getAppIcon(Activity activity) {
        try {
            PackageManager pm = activity.getPackageManager();
            ApplicationInfo info = pm.getApplicationInfo(activity.getPackageName(), 0);
            return info.icon;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return R.drawable.umengsocialize_more_share_yxtsdk;
    }

    /**
     * 分享统一UI 订制,可以控制图标之间距离 by liyue 2017-10-19
     *
     * @param activity
     * @param share_types1    --- 分享平台设置
     * @param imgUrl          --- 图片 url
     * @param title           --- 标题
     * @param text            --- 内容
     * @param shareCallBack-- 回调
     */
    public static void shareWithWindows(final Activity activity, SHARE_TYPE[] share_types1,
                                        final String imgUrl, final String title, final String text,
                                        final String targetUrl, final ShareCallBack shareCallBack) {
        SHARE_TYPE[] share_types = share_types1.clone();
        switch (activity.getPackageName()) {
            case "com.yxt.phoenix.ceibsonline":
                List<SHARE_TYPE> shareTypes = new ArrayList<>();
                for (SHARE_TYPE s : share_types1) {
                    if (!s.equals(SHARE_TYPE.WECHAT_FRIENDS) && !s.equals(SHARE_TYPE.WECHAT_MOMENTS) && !s.equals(SHARE_TYPE.COPY)) {
                        shareTypes.add(s);
                    }
                }
                share_types = new SHARE_TYPE[shareTypes.size()];
                for (int i = 0; i < shareTypes.size(); i++) {
                    share_types[i] = shareTypes.get(i);
                }
                break;
        }
        //SharePopuWindow
        SharePopupWindow menuWindow = new SharePopupWindow(activity, share_types, new SharePopupWindow.PopupWindowItemClick() {
            @Override
            public void clickCallBack(int pos, SHARE_TYPE share_type) {
                if (shareCallBack != null) {
                    shareCallBack.onClick(pos, share_type);
                }
                if (share_type == SHARE_TYPE.COPY) {
                    ClipboardManager clipboard = (ClipboardManager)
                            activity.getSystemService(Context.CLIPBOARD_SERVICE);
                    clipboard.setPrimaryClip(ClipData.newPlainText(null, targetUrl));
                    // clipboard.setText(targetUrl);
                    PHToast.shotBigToast(activity, "已复制");
                    return;
                }

                if (share_type == SHARE_TYPE.WECHAT_FRIENDS || share_type == SHARE_TYPE.WECHAT_MOMENTS) {
                    if (!UMShareAPI.get(activity).isInstall(activity, SHARE_MEDIA.WEIXIN)) {
                        PHToast.showSingleToast(activity, activity.getString(R.string.common_yxt_msg_weixinuninstall));
                        return;
                    }
                }
                share(activity, share_type, imgUrl, title, text, targetUrl, shareCallBack);
            }
        });
        //设置layout在PopupWindow中显示的位置
        menuWindow.showAtLocation(activity.getWindow().getDecorView().findViewById(android.R.id.content), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equalsIgnoreCase("com.tencent.qqlite") || pn.equalsIgnoreCase("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 分享完成回调
     *
     * @param context
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public static void onActivityResult(Context context, int requestCode, int resultCode, Intent data) {
        /** attention to this below ,must add this**/
        UMShareAPI.get(context).onActivityResult(requestCode, resultCode, data);
        Log.e("TAG", "onActivityResult");
    }

    /**
     * 在使用分享或者授权的Activity中，重写onDestory()方法：
     *
     * @param context
     */
    public static void onDestroy(Context context) {
        UMShareAPI.get(context).release();
    }

    /***
     * @param activity
     * @param share_type
     */
    public static boolean isInstall(Activity activity, SHARE_TYPE share_type) {
        return UMShareAPI.get(activity).isInstall(activity, getShareMedia(share_type));
    }

    public void share(Activity context, String imgUrl, String title, String text, String targetUrl) {
        SHARE_TYPE[] share_types = new SHARE_TYPE[]{SHARE_TYPE.WECHAT_MOMENTS, SHARE_TYPE.WECHAT_FRIENDS, SHARE_TYPE.QQ, SHARE_TYPE.COPY};
        shareWithWindows(context, share_types,
                imgUrl, title, text,
                targetUrl, new ShareCallBack() {

                    @Override
                    public void onResult(SHARE_TYPE shareType) {

                    }

                    @Override
                    public void onSuccess(SHARE_TYPE shareType) {

                    }

                    @Override
                    public void onError(SHARE_TYPE shareType, Throwable exception) {

                    }

                    @Override
                    public void onCancel(SHARE_TYPE shareType) {

                    }

                    @Override
                    public void onClick(int which, SHARE_TYPE shareType) {

                    }
                });
    }


    /**
     * 分享 监听 类
     */
    private static class ShareListener implements UMShareListener {
        Activity activity;
        ShareCallBack shareCallBack;

        public ShareListener(Activity activity, ShareCallBack shareCallBack) {
            this.activity = activity;
            this.shareCallBack = shareCallBack;
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.e("TAG", "platform" + platform);
            if (shareCallBack != null) {
                shareCallBack.onResult(getShareType(platform));
            }
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(activity, platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
//                Toast.makeText(activity, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                if (shareCallBack != null) {
                    shareCallBack.onSuccess(getShareType(platform));
                }
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
//            Toast.makeText(activity, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (shareCallBack != null) {
                shareCallBack.onError(getShareType(platform), t);
            }
            if (t != null) {
                Log.e("TAG", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            if (shareCallBack != null) {
                shareCallBack.onCancel(getShareType(platform));
            }
//            Toast.makeText(activity, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onStart(SHARE_MEDIA share_media) {
        }

    }

    /***
     * 根据shareType获取shareMedia
     * @param share_type
     * @return
     */
    private static SHARE_MEDIA getShareMedia(SHARE_TYPE share_type) {
        if (share_type == SHARE_TYPE.QQ) {
            return SHARE_MEDIA.QQ;
        } else if (share_type == SHARE_TYPE.WECHAT_FRIENDS) {
            return SHARE_MEDIA.WEIXIN;
        } else if (share_type == SHARE_TYPE.WECHAT_MOMENTS) {
            return SHARE_MEDIA.WEIXIN_CIRCLE;
        }
        return SHARE_MEDIA.MORE;
    }

    /***
     * 根据shareMedia获取shareType
     * @param share_media
     * @return
     */
    private static SHARE_TYPE getShareType(SHARE_MEDIA share_media) {
        if (share_media == SHARE_MEDIA.QQ) {
            return SHARE_TYPE.QQ;
        } else if (share_media == SHARE_MEDIA.WEIXIN) {
            return SHARE_TYPE.WECHAT_FRIENDS;
        } else if (share_media == SHARE_MEDIA.WEIXIN_CIRCLE) {
            return SHARE_TYPE.WECHAT_MOMENTS;
        }
        return SHARE_TYPE.MORE;
    }


}
